/*
   WinMgr.cs
   Created by Randall Maas, Saturday January 31 2009
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System ;
using System . Runtime . InteropServices;
using System . Text;
using System . Diagnostics;

enum GA
{
   PARENT = 1,
   ROOT = 2,
   ROOTOWNER = 3
};

public static partial class Win32
{
   #region Window Hierarchy
   [DllImport("user32.dll", SetLastError = true)]
   internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

   [DllImport("user32.dll", SetLastError = true)]
   internal static extern IntPtr GetParent(IntPtr hWnd);

#if false
   // Don't use: use GetParent (above) instead

   static IntPtr WinParent(IntPtr Win)
   {
      return GetWindowLongPtr(Win, GWL . HWNDPARENT);
   }
#endif


   /// <summary>
   /// Retrieves the desktop's window handle; often this is the most ancestory
   /// of windows
   /// </summary>
   /// <returns>Handle</returns>
   [DllImport("user32.dll")]
   internal static extern IntPtr GetDesktopWindow();

   /// <summary>
   /// Cached version of the desktop window
   /// </summary>
   internal static IntPtr desktopWin;


   /// <summary>
   /// Retrieves the "parent" or other ancestor of the specified window
   /// </summary>
   /// <param name="hwnd">The item we are interested in</param>
   /// <param name="Flags">The type of ancestore</param>
   /// <returns></returns>
   [DllImport("user32.dll", ExactSpelling=true)]
   static extern IntPtr GetAncestor(IntPtr hwnd, GA Flags);

   /// <summary>
   /// Gets the application that owns the specified windows handle
   /// </summary>
   /// <param name="Handle"></param>
   /// <returns></returns>
   internal static IntPtr AppAncestor(IntPtr Handle)
   {
      if (IntPtr . Zero == desktopWin)
        desktopWin = GetDesktopWindow();

      IntPtr tempWin = Handle;
      while (tempWin != IntPtr.Zero && tempWin != desktopWin)
      {
         Handle = tempWin;
         tempWin = GetAncestor(tempWin, GA . PARENT);
      }
      return Handle;
   }
// todo: does win instance work any better?


   /// <summary>
   /// Retrieves the application instance
   /// </summary>
   /// <param name="Win"></param>
   /// <returns>Handle to the application instance</returns>
   internal static IntPtr WinInstance(IntPtr Win)
   {
      return GetWindowLongPtr(Win, GWL . HINSTANCE);
   }


   #endregion

   #region Z order
   /// <summary>
   /// Gets the handle of the foreground window -- the user is currently using it
   /// </summary>
   /// <returns>Window Handle</returns>
   [DllImport("user32.dll")]
   internal static extern IntPtr GetForegroundWindow();

   /// <summary>
   /// This is used to set the foreground dinw
   /// </summary>
   /// <param name="Wnd">Handle of the window to make the forground</param>
   /// <returns></returns>
   [DllImport("user32.dll")]
   static extern Int32 SetForegroundWindow(IntPtr Wnd);

   /// <summary>
   /// 
   /// </summary>
   /// <param name="Wnd"></param>
   /// <param name="fAltTab"></param>
   /// <remarks>Deprecated</remarks>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/SwitchToThisWindow.html" />
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms633553%28VS.85%29.aspx" />
   [DllImport("user32.dll", SetLastError=true)]
   static extern void SwitchToThisWindow(IntPtr Wnd, [MarshalAs(UnmanagedType.Bool)] bool fAltTab);


   internal static bool SwitchTo(IntPtr Wnd)
   {
      // First try plain SetForegroundWindow
      SetForegroundWindow(Wnd);
      if (GetForegroundWindow() == Wnd)
        return true;
      SwitchToThisWindow(Wnd, false);
      return true;
   }


   /// <summary>
   /// Gets the handle of window active for the current input queue -- ie
   /// the calling thread. See also GetFocus()
   /// </summary>
   /// <remarks>For the active window across processes, see GetForegroundWindow</remarks>
   /// <returns>Window Handle</returns>
   [DllImport("user32.dll")]
   internal static extern IntPtr GetActiveWindow();


   /// <summary>
   /// 
   /// </summary>
   /// <param name="hWnd"></param>
   /// <returns></returns>
   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   internal static extern bool BringWindowToTop(IntPtr hWnd);


   const int ASFW_ANY = -1;
   const uint LSFW_LOCK= 1;
   const uint LSFW_UNLOCK= 2;

   /// <summary>
   /// 
   /// </summary>
   /// <param name="LockCode"></param>
   /// <returns></returns>
   [DllImport("user32.dll", SetLastError = true)]
   [return: MarshalAs(UnmanagedType.Bool)]
   internal static extern bool LockSetForegroundWindow(UInt32 LockCode);

   /// <summary>
   /// 
   /// </summary>
   /// <param name="hWnd"></param>
   /// <param name="lpClassName"></param>
   /// <param name="nMaxCount"></param>
   /// <returns></returns>
   [DllImport("user32.dll", SetLastError = true, CharSet=CharSet.Unicode)]
   static extern Int32 GetClassName(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpClassName, UInt32 nMaxCount);
   #endregion


#if false 
   static void ForWin(IntPtr Handle)
   {

      Handle = RootAncestor(Handle);
      string Title = WinTitle(Handle);
      if (win != lastWin || title != lastEntry.title)
        {
           lastWin = win;
           if (lastEntry.procName != null)
             {
                lastEntry.timeSpan = DateTime.Now - lastEntry.dateTime;
                WriteLastEntry();
             }
           Process p = WinProcess(Handle);
           string procName = p.ProcessName;
           //now title is the win title and procName is the EXE
           lastEntry.dateTime = DateTime.Now;
           lastEntry.procName = procName;
           lastEntry.title = title;
        }
   }
#endif


   #region Minimize / Maxmize / etc
   /// <summary>
   /// Window to minimize, maximize, restore
   /// </summary>
   /// <param name="Wnd">Window to set</param>
   /// <param name="nCmdShow"></param>
   /// <returns>0 on error, otherwise success</returns>
   [DllImport("user32.dll")]
   static extern int ShowWindow(IntPtr Wnd, SW nCmdShow);

   /// <summary>
   /// Activates the window and displays it as a minimized window.
   /// </summary>
   /// <param name="Wnd">Window to set</param>
   /// <returns>0 on error, otherwise success</returns>
   internal static int Minimize(IntPtr Wnd)
   {
      return ShowWindow(Wnd, SW . ShowMinimized);
   }

   /// <summary>
   /// Activates the window and displays it as a maximized window.
   /// </summary>
   /// <param name="Wnd">Window to set</param>
   /// <returns>0 on error, otherwise success</returns>
   internal static int Maximize(IntPtr Wnd)
   {
      return ShowWindow(Wnd, SW . ShowMaximized);
   }

   /// <summary>
   /// Activates and displays a window. If the window is minimized or
   /// maximized, the system restores it to its original size and position.
   /// An application should specify this flag when displaying the window
   /// for the first time.
   /// </summary>
   /// <param name="Wnd">Window to set</param>
   /// <returns>0 on error, otherwise success</returns>
   internal static int Normal(IntPtr Wnd)
   {
      return ShowWindow(Wnd, SW . Normal);
   }

   /// <summary>
   /// Activates and displays the window. If the window is minimized or
   /// maximized, the system restores it to its original size and position.
   /// An application should specify this flag when restoring a minimized window.
   /// </summary>
   /// <param name="Wnd">Window to set</param>
   /// <returns>0 on error, otherwise success</returns>
   internal static int Restore(IntPtr Wnd)
   {
      return ShowWindow(Wnd, SW . Restore);
   }
   #endregion
}

